package edu.dublbo.app.habitplusfavorite.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.dublbo.app.habitplusfavorite.mapper.VisitorLastHistoryMapper;
import edu.dublbo.app.habitplusfavorite.model.VisitorLastHistory;
import edu.dublbo.app.habitplusfavorite.service.IVisitorLastHistoryService;
import edu.dublbo.app.habitplusfavorite.vo.VisitDataVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 访客的最近一次访问的历史 服务实现类
 * </p>
 *
 * @author habitplus
 * @since 2021-11-30
 */
@Service
@Slf4j
public class VisitorLastHistoryServiceImpl extends ServiceImpl<VisitorLastHistoryMapper, VisitorLastHistory> implements IVisitorLastHistoryService {

    @Override
    public void add(String hostIp, String requestPath) {
        if (StringUtils.isNotBlank(hostIp) && StringUtils.isNotBlank(requestPath)) {
            // 找以前是否有访问过
            VisitorLastHistory oldHis = baseMapper.selectOne(
                    Wrappers.<VisitorLastHistory>lambdaQuery()
                            .eq(VisitorLastHistory::getHostIp, hostIp)
                            .eq(VisitorLastHistory::getVisitedPath, requestPath));
            if (oldHis == null) {
                VisitorLastHistory his = new VisitorLastHistory();
                his.setHostIp(hostIp);
                his.setVisitedPath(requestPath);
                his.setVisitedDate(new Date());
                his.setVisitedCount(1L);
                baseMapper.insert(his);
            } else {
                oldHis.setVisitedDate(new Date());
                long count = oldHis.getVisitedCount() + 1;
                oldHis.setVisitedCount(count);
                baseMapper.updateById(oldHis);
            }
        }
    }

    @Override
    public VisitDataVo statics(String pageUrl) {
        long totalVisitPv = baseMapper.getTotalVisitPv(pageUrl);
        long totalVisitUv = baseMapper.getTotalVisitUv(pageUrl);
        VisitDataVo visitDataVo = new VisitDataVo();
        visitDataVo.setPv(totalVisitPv);
        visitDataVo.setUv(totalVisitUv);
        return visitDataVo;
    }
}
